<template>
  <div class="permission-feature">
    <BaseList
      title="功能权限列表"
      :add-permission="'permission:feature:add'"
      :loading="loading"
      :data="tableData"
      :search-fields="searchFields"
      :pagination="pagination"
      :debounce-delay="300"
      row-key="permissionId"
      children-key="children"
      @search="handleSearch"
      @reset="handleReset"
      @add="handleAdd"
      @update:pagination="handlePaginationChange"
    >
      <template #columns>
        <a-table-column title="权限名称" data-index="permissionName">
          <template #cell="{ record }">
            <a-space>
              <component :is="getIcon(record.icon)" v-if="record.icon" />
              {{ record.permissionName }}
            </a-space>
          </template>
        </a-table-column>
        <a-table-column title="权限编码" data-index="permissionCode" />
        <a-table-column title="权限类型" data-index="permissionType">
          <template #cell="{ record }">
            <a-tag :color="getPermissionTypeColor(record.permissionType)">
              {{ getPermissionTypeText(record.permissionType) }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="组件路径" data-index="component" />
        <a-table-column title="路由路径" data-index="path" />
        <a-table-column title="是否外链" data-index="isFrame">
          <template #cell="{ record }">
            <a-tag :color="record.isFrame === 1 ? 'orange' : 'cyan'">
              {{ record.isFrame === 1 ? '是' : '否' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="显示顺序" data-index="orderNum" />
        <a-table-column title="等级" data-index="permissionLevel" />
        <a-table-column title="显示状态" data-index="visible">
          <template #cell="{ record }">
            <a-tag :color="record.visible === 1 ? 'blue' : 'gray'">
              {{ record.visible === 1 ? '显示' : '隐藏' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="状态" data-index="permissionStatus">
          <template #cell="{ record }">
            <a-tag :color="record.permissionStatus === 1 ? 'green' : 'red'">
              {{ record.permissionStatus === 1 ? '正常' : '停用' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" :width="240">
          <template #cell="{ record }">
            <a-space>
              <BaseButton
                type="outline"
                size="mini"
                @click="handleEdit(record)"
                v-permission="'permission:feature:edit'"
              >
                <template #icon>
                  <BaseIcon name="IconEdit" />
                </template>
                编辑
              </BaseButton>
              <BaseButton
                v-if="record.permissionType !== 3"
                type="outline"
                size="mini"
                @click="handleAddButton(record)"
                v-permission="'permission:feature:add'"
              >
                <template #icon>
                  <BaseIcon name="icon-plus" />
                </template>
                新增
              </BaseButton>
              <BaseButton
                type="outline"
                size="mini"
                :status="record.permissionStatus === 1 ? 'danger' : 'success'"
                @click="handleModifyStatus(record)"
                v-permission="'permission:feature:status'"
              >
                <template #icon>
                  <BaseIcon name="IconPoweroff" v-if="record.permissionStatus === 1" />
                  <BaseIcon name="IconPlayCircle" v-else />
                </template>
                {{ record.permissionStatus === 1 ? '停用' : '启用' }}
              </BaseButton>
              <BaseButton
                type="outline"
                size="mini"
                status="danger"
                :loading="loading"
                @click="handleDelete(record)"
                v-permission="'permission:feature:delete'"
              >
                <template #icon>
                  <BaseIcon name="IconDelete" />
                </template>
                删除
              </BaseButton>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </BaseList>

    <LoadingSpinner :visible="loading" text="加载中..." />

    <!-- 添加/编辑权限弹窗 -->
    <BaseForm
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :loading="loading"
      v-model="formData"
      :rules="rules"
      @cancel="handleCancel"
      @submit="handleSubmit"
    >
      <template #form-items>
        <a-form-item
          label="权限名称"
          field="permissionName"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input
            v-model="formData.permissionName"
            placeholder="请输入权限名称"
            size="large"
            allow-clear
          />
        </a-form-item>

        <a-form-item
          label="图标"
          field="icon"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <icon-selector v-model="formData.icon" />
        </a-form-item>

        <a-form-item
          label="权限编码"
          field="permissionCode"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input
            v-model="formData.permissionCode"
            placeholder="请输入权限编码"
            size="large"
            allow-clear
          />
        </a-form-item>

        <a-form-item
          label="权限类型"
          field="permissionType"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-select
            v-model="formData.permissionType"
            placeholder="请选择权限类型"
            size="large"
            :disabled="!isAdd && formData.permissionType === 0"
          >
            <a-option
              v-for="option in getPermissionTypeOptions()"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="是否外链"
          field="isFrame"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-radio-group v-model="formData.isFrame" size="large">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          label="路由路径"
          field="path"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input
            v-model="formData.path"
            :placeholder="formData.isFrame === 1 ? '请输入外链地址' : '请输入路由路径'"
            size="large"
            allow-clear
          />
        </a-form-item>

        <a-form-item
          label="组件路径"
          field="component"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input
            v-model="formData.component"
            placeholder="请输入组件路径"
            size="large"
            allow-clear
          />
        </a-form-item>

        <a-form-item
          label="显示顺序"
          field="orderNum"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input-number
            v-model="formData.orderNum"
            placeholder="请输入显示顺序"
            size="large"
            :min="1"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item
          label="显示状态"
          field="visible"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-radio-group v-model="formData.visible" size="large">
            <a-radio :value="1">显示</a-radio>
            <a-radio :value="2">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="isAdd || isAddButton"
          label="父级权限"
          field="parentId"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-select
            v-model="formData.parentId"
            placeholder="请选择父级权限"
            size="large"
            :disabled="!!formData.parentId && isAddButton"
          >
            <a-option
              v-for="option in parentOptions"
              :key="option.value"
              :value="option.value"
              :disabled="option.disabled"
            >
              {{ option.label }}
            </a-option>
          </a-select>
        </a-form-item>
      </template>
    </BaseForm>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import BaseList from '@/components/BaseList.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import { useNotification } from '@/composables/useNotification'
import { filterEmptyValue } from '@/utils/object'
import BaseButton from '@/components/BaseButton.vue'
import type { FormInstance } from '@arco-design/web-vue'
import { Modal } from '@arco-design/web-vue'
import BaseForm from '@/components/BaseForm.vue'
import { permissionFeatureService } from '@/services/permissionFeature'
import type {
  PermissionFeatureTreePageParam,
  PermissionFeatureTreeResponse,
  PermissionFeatureRequest,
  PermissionSelectOption,
} from '@/types/permissionFeature'
import { getIcon } from '@/composables/useIcons'
import IconSelector from '@/components/IconSelector.vue'
import BaseIcon from '@/components/BaseIcon.vue'

const loading = ref(false)
const tableData = ref<PermissionFeatureTreeResponse[]>([])
const notify = useNotification()

// 定义搜索字段
const searchFields = [
  {
    key: 'permissionName',
    placeholder: '请输入权限名称',
    icon: getIcon('IconSearch'),
  },
  {
    key: 'permissionCode',
    placeholder: '请输入权限编码',
    icon: getIcon('IconSearch'),
  },
  {
    key: 'permissionLevel',
    placeholder: '请选择权限等级',
    type: 'select',
    options: [
      { label: '一级', value: 1 },
      { label: '二级', value: 2 },
      { label: '三级', value: 3 },
      { label: '四级', value: 4 },
      { label: '五级', value: 5 },
      { label: '六级', value: 6 },
    ],
  },
]

// 分页信息
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
})

// 表单相关
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const dialogTitle = ref('新增权限')
const isAdd = ref(true)
const isAddButton = ref(false)
const parentOptions = ref<PermissionSelectOption[]>([])

// 表单数据
const formData = reactive<PermissionFeatureRequest>({
  permissionId: '',
  parentId: '',
  permissionCode: '',
  permissionName: '',
  permissionType: 1,
  component: '',
  path: '',
  orderNum: 1,
  visible: 1,
  icon: '',
  permissionStatus: 1,
  isFrame: 2,
})

// 表单校验规则
const rules = {
  permissionName: [{ required: true, message: '请输入权限名称' }],
  permissionCode: [{ required: true, message: '请输入权限编码' }],
  permissionType: [{ required: true, message: '请选择权限类型' }],
  path: [
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (formData.isFrame === 1 && !value) {
          callback('外链时路由路径必填')
        } else {
          callback()
        }
      },
    },
  ],
}

/** 获取权限类型文本 */
const getPermissionTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    0: '系统',
    1: '目录',
    2: '菜单',
    3: '按钮',
  }
  return typeMap[type] || '未知'
}

/** 获取权限类型颜色 */
const getPermissionTypeColor = (type: number) => {
  const colorMap: Record<number, string> = {
    0: 'purple',
    1: 'blue',
    2: 'green',
    3: 'orange',
  }
  return colorMap[type] || 'default'
}

/** 获取权限表数据 */
const fetchData = async (searchParams: Partial<PermissionFeatureTreePageParam> = {}) => {
  loading.value = true
  try {
    const params: PermissionFeatureTreePageParam = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...filterEmptyValue(searchParams),
    }
    const res = await permissionFeatureService.getPermissionFeatureTree(params)
    tableData.value = res.list
    parentOptions.value = transformToOptions(res.list)
    pagination.value = {
      ...pagination.value,
      current: res.pageNum,
      total: res.total,
      pageSize: res.pageSize,
    }
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : '获取权限列表失败'
    notify.error(errorMessage)
    console.error('获取限列表出错:', err)
  } finally {
    loading.value = false
  }
}

// 保存当前搜索条件
const currentSearchParams = ref<Partial<PermissionFeatureTreePageParam>>({})

/** 搜索处理 */
const handleSearch = (form: Partial<PermissionFeatureTreePageParam>) => {
  pagination.value.current = 1
  currentSearchParams.value = form
  fetchData(form)
}

/** 重置处理 */
const handleReset = () => {
  pagination.value.current = 1
  fetchData()
}

/** 新增权限 */
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增权限'
  isAdd.value = true
  isAddButton.value = false
  resetForm()
}

/** 编辑权限 */
const handleEdit = (record: PermissionFeatureTreeResponse) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑权限'
  isAdd.value = false
  Object.assign(formData, record)
}

/** 删除权限 */
const handleDelete = (record: PermissionFeatureTreeResponse) => {
  Modal.warning({
    title: '确认删除',
    content: `确定要删除权限 "${record.permissionName}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    hideCancel: false,
    async onOk() {
      try {
        loading.value = true
        await permissionFeatureService.deletePermissionFeature(record.permissionId)
        notify.success('删除权限成功')
        fetchData()
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '删除权限失败'
        notify.error(errorMessage)
      } finally {
        loading.value = false
      }
    },
  })
}

/** 修改状态 */
const handleModifyStatus = (record: PermissionFeatureTreeResponse) => {
  const newStatus = record.permissionStatus === 1 ? 2 : 1
  const actionText = record.permissionStatus === 1 ? '停用' : '启用'

  Modal.warning({
    title: `确认${actionText}`,
    content: `确定要${actionText}权限 "${record.permissionName}" 吗？ (注意: 该操作将影响该权限下的所有子权限)`,
    okText: '确定',
    cancelText: '取消',
    hideCancel: false,
    async onOk() {
      try {
        loading.value = true
        await permissionFeatureService.modifyStatus({
          permissionId: record.permissionId,
          permissionStatus: newStatus,
        })
        notify.success(`${actionText}成功`)
        fetchData()
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : `${actionText}失败`
        notify.error(errorMessage)
      } finally {
        loading.value = false
      }
    },
  })
}

/** 提交表单 */
const handleSubmit = async () => {
  try {
    // 外链时路径必填的额外验证
    if (formData.isFrame === 1 && !formData.path) {
      notify.warning('外链时路由路径必填')
      return false
    }

    loading.value = true
    if (isAdd.value) {
      await permissionFeatureService.createPermissionFeature(formData as PermissionFeatureRequest)
      notify.success('新增权限成功')
    } else {
      await permissionFeatureService.modifyPermissionFeature(formData as PermissionFeatureRequest)
      notify.success('修改权限成功')
    }
    dialogVisible.value = false
    fetchData()
    return true
  } catch (err) {
    const errorMessage =
      err instanceof Error ? err.message : `${isAdd.value ? '新增' : '修改'}权限失败`
    notify.error(errorMessage)
    return false
  } finally {
    loading.value = false
  }
}

/** 取消操作 */
const handleCancel = () => {
  dialogVisible.value = false
  isAddButton.value = false
  resetForm()
}

/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
  isAdd.value = true
  Object.assign(formData, {
    permissionId: '',
    parentId: '',
    permissionCode: '',
    permissionName: '',
    permissionType: 1,
    component: '',
    path: '',
    orderNum: 1,
    visible: 1,
    icon: '',
    permissionStatus: 1,
    isFrame: 2,
  })
}

/** 分页变化处理 */
const handlePaginationChange = (newPagination: typeof pagination.value) => {
  pagination.value = newPagination
  fetchData(currentSearchParams.value)
}

// 转换权限数据为选择项
const transformToOptions = (data: PermissionFeatureTreeResponse[]): PermissionSelectOption[] => {
  return data.flatMap((item) => {
    const option: PermissionSelectOption = {
      label: item.permissionName,
      value: item.permissionId,
      type: item.permissionType,
      disabled: item.permissionType === 3,
    }
    const children = item.children ? transformToOptions(item.children) : []
    return [option, ...children]
  })
}

// 添加新增方法
const handleAddButton = (record: PermissionFeatureTreeResponse) => {
  isAddButton.value = true
  isAdd.value = true
  dialogVisible.value = true
  dialogTitle.value = '新增权限'
  resetForm()
  formData.parentId = record.permissionId
  formData.permissionType = 3
}

// 新增获取权限类型选项的方法
const getPermissionTypeOptions = () => {
  // 如果是编辑模式且当前是系统类型，则显示系统选项
  if (!isAdd.value && formData.permissionType === 0) {
    return [{ label: '系统', value: 0 }]
  }
  // 新增模式只显示目录、菜单、按钮
  return [
    { label: '目录', value: 1 },
    { label: '菜单', value: 2 },
    { label: '按钮', value: 3 },
  ]
}

// 修改 watch 监听逻辑
watch(
  () => formData.isFrame,
  (newValue) => {
    // 清除之前的验证状态
    formRef.value?.clearValidate(['path'])
    // 如果是外链，则重新验证路径
    if (newValue === 1) {
      formRef.value?.validate((errors) => {
        if (errors?.path) {
          notify.warning('外链时路由路径必填')
        }
      })
    }
  },
)

// 初始加载
fetchData()
</script>
